<template>
        <!-- <a-select v-model:value='value' show-search :field-names="{label:'name', value:'code'}" :filter-option="filterOption" :options='i18n.langOptions'></a-select> -->
        <a-auto-complete v-model:value='value' :options="options" @search="onSearch" @select="onSelect" />

</template>
<script lang="ts" setup>
    import { useI18nStore } from '@/store/i18n';
    import { ref } from 'vue';

    const i18n = useI18nStore()

    const props = defineProps<{
        modelValue:string;
    }>()

    const emit = defineEmits<{
        (e : 'update:modelValue', value:string) : void
    }>()

    const value = ref()

    if(props.modelValue) {
        let v = props.modelValue
        for(let i = 0; i < i18n.langOptions.length; i ++) {
            if(i18n.langOptions[i].code == props.modelValue) {
                v = i18n.langOptions[i].name
                break
            }
        }

        value.value = v
    }

    function change(v) {
        emit('update:modelValue', v)
    }

    

    // function filterOption(input:string, options) {
    //     return options.name.indexOf(input) >= 0;
    // }




    interface Option {
        value: string;
    }
    
    const options = ref<Option[]>([])
    const optionMap = new Map()
        
    const onSelect = (v: string) => {
        change(optionMap.get(v))
    };


    function onSearch(searchText: string){
        let v = searchText
        optionMap.clear()
        options.value = []
        if(searchText) {
            i18n.langOptions.forEach(option => {
                const name = option.name.toLocaleLowerCase()
                const text = searchText.toLocaleLowerCase()
                optionMap.set(option.name, option.code)
                if(name == text) {
                    v = option.code
                }
                if(name.includes(text)) {
                    options.value.push({value : option.name})
                }
            })
        }
        

        change(v)
    };

</script>